import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:go_router/go_router.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/store/index.dart';
import 'package:flutter_mobx/flutter_mobx.dart';

class ChatListPage extends StatefulWidget {
  const ChatListPage({super.key});

  @override
  State<ChatListPage> createState() => _ChatListPageState();
}

class _ChatListPageState extends State<ChatListPage>
    with SingleTickerProviderStateMixin {
  final _rootStore = RootStore();
  late final PageController _pageController;
  late final TabController _tabController;
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    _tabController = TabController(length: 2, vsync: this);

    // 加载聊天列表数据
    _loadChatList();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  // 加载聊天列表
  Future<void> _loadChatList() async {
    await _rootStore.chatListStore.loadChatSessions();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFA794FD), Color(0xFFFFEFFA)],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部标题栏
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        // 使用安全的导航方式
                        final router = GoRouter.of(context);
                        if (router.canPop()) {
                          router.pop();
                        } else {
                          router.go('/');
                        }
                      },
                      child: Icon(
                        IconFont.back,
                        color: Colors.white,
                        size: 28.w,
                      ),
                    ),
                    SizedBox(width: 16.w),
                    Text(
                      'Chat List',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),

              // 标签切换
              Padding(
                padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 10.h),
                child: Row(
                  children: [
                    _buildTabButton('Chat', 0),
                    SizedBox(width: 20.w),
                    _buildTabButton('Group Chat', 1),
                  ],
                ),
              ),

              // 聊天列表
              Expanded(
                child: PageView(
                  controller: _pageController,
                  onPageChanged: (index) {
                    if (_currentIndex != index) {
                      setState(() {
                        _currentIndex = index;
                      });
                    }
                  },
                  physics: const ClampingScrollPhysics(),
                  children: [_buildPrivateChatList(), _buildGroupChatList()],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建标签按钮
  Widget _buildTabButton(String title, int index) {
    bool isSelected = _currentIndex == index;

    return GestureDetector(
      onTap: () {
        if (!isSelected) {
          setState(() {
            _currentIndex = index;
          });

          _pageController.animateToPage(
            index,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
          );
        }
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              title,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
              ),
            ),
            SizedBox(height: 4.h),
            // 选中指示器
            TweenAnimationBuilder<double>(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              tween: Tween<double>(
                begin: isSelected ? 0.0 : 1.0,
                end: isSelected ? 1.0 : 0.0,
              ),
              builder: (context, value, child) {
                return Container(
                  height: 2.h,
                  width: 40.w,
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(value),
                    borderRadius: BorderRadius.circular(1.r),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  // 构建群聊列表
  Widget _buildGroupChatList() {
    return Observer(
      builder: (_) {
        final groupChats = _rootStore.chatListStore.groupChats;
        final isLoading = _rootStore.chatListStore.isLoading;

        if (isLoading) {
          return Center(child: CircularProgressIndicator(color: Colors.white));
        }

        if (groupChats.isEmpty) {
          return _buildEmptyState('No group chats yet');
        }

        return ListView.builder(
          itemCount: groupChats.length,
          padding: EdgeInsets.symmetric(vertical: 10.h),
          itemBuilder: (context, index) {
            final chat = groupChats[index];
            return FutureBuilder<ChatMessageModel?>(
              future: _rootStore.chatListStore.getLatestMessage(chat.id),
              builder: (context, snapshot) {
                final lastMessage = snapshot.data;
                String messageText = '';

                if (lastMessage != null) {
                  // 获取发送者名称
                  final sender = UserService.getUserById(lastMessage.senderId);
                  final senderName = sender?.nickname ?? 'Unknown';

                  if (lastMessage.type == MessageType.text) {
                    // 文本消息格式：用户名：消息内容
                    messageText = '${senderName}: ${lastMessage.text ?? ''}';
                  } else if (lastMessage.type == MessageType.perfumeCard) {
                    // 香水卡片消息格式：用户名：[perfume]
                    messageText = '${senderName}: [perfume]';
                  }
                } else {
                  // 没有消息的情况
                  messageText = '开始聊天吧...';
                }

                return _buildChatItem(chat: chat, lastMessage: messageText);
              },
            );
          },
        );
      },
    );
  }

  // 构建私聊列表
  Widget _buildPrivateChatList() {
    return Observer(
      builder: (_) {
        final privateChats = _rootStore.chatListStore.privateChats;
        final isLoading = _rootStore.chatListStore.isLoading;

        if (isLoading) {
          return Center(child: CircularProgressIndicator(color: Colors.white));
        }

        if (privateChats.isEmpty) {
          return _buildEmptyState('No private chats yet');
        }

        return ListView.builder(
          itemCount: privateChats.length,
          padding: EdgeInsets.symmetric(vertical: 10.h),
          itemBuilder: (context, index) {
            final chat = privateChats[index];
            return FutureBuilder<ChatMessageModel?>(
              future: _rootStore.chatListStore.getLatestMessage(chat.id),
              builder: (context, snapshot) {
                final lastMessage = snapshot.data;
                String messageText = '';

                if (lastMessage != null) {
                  if (lastMessage.type == MessageType.text) {
                    messageText = lastMessage.text ?? '';
                  } else if (lastMessage.type == MessageType.perfumeCard) {
                    messageText = '[perfume]';
                  }
                } else {
                  // 没有消息的情况
                  messageText = 'Start chatting...';
                }

                return _buildChatItem(chat: chat, lastMessage: messageText);
              },
            );
          },
        );
      },
    );
  }

  // 构建空状态
  Widget _buildEmptyState(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            AssetsImages.empty,
            width: 120.w,
            height: 120.w,
            fit: BoxFit.contain,
          ),
          SizedBox(height: 20.h),
          Text(
            message,
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white.withOpacity(0.7),
            ),
          ),
        ],
      ),
    );
  }

  // 构建聊天项
  Widget _buildChatItem({
    required ChatSessionModel chat,
    required String lastMessage,
  }) {
    return InkWell(
      onTap: () {
        // 导航到聊天详情页
        context.push('/chat/${chat.id}');
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
        child: Row(
          children: [
            // 头像
            Container(
              width: 42.w,
              height: 42.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: AssetImage(chat.avatar ?? AssetsImages.avatar1),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SizedBox(width: 12.w),

            // 聊天信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    chat.name,
                    style: TextStyle(
                      fontSize: 15.sp,
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                      fontFamily: 'Inter',
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    lastMessage,
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: Colors.white.withOpacity(0.7),
                      fontFamily: 'Inter',
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),

            // 右箭头
            Icon(Icons.arrow_forward_ios, color: Colors.white, size: 16.w),
          ],
        ),
      ),
    );
  }
}
